package Socket.TCP;

import com.Utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class MyClient {

    public static void main(String... args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            Socket socket = new Socket("localhost", 8080);
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                //发送请求
                outputStream = socket.getOutputStream();
                outputStream.write(msg.getBytes());
                outputStream.flush();
                //结束输出流
                socket.shutdownOutput();
                //响应
                inputStream = socket.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int len;
                while ((len = inputStream.read(buf)) > -1) {
                    baos.write(buf, 0, len);
                }
                System.out.println("接收到响应：" + new String(baos.toByteArray()));
            } finally {
                Utils.doClose(inputStream);
                Utils.doClose(outputStream);
                Utils.doClose(socket);
            }
        }
    }

}
